package org.imaginedays.androidall.utils;



import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

public class FetchVideoUrlUtil {
	
	private static final String HOST_URL = "http://www.yinyuetai.com";
	private static final String BASE_URL = "http://www.yinyuetai.com/search?searchType=mv&keyword=";
	private static final String VIDEO_LIST_XPATH = "//div[@class='thumb thumb_mv']//a";
	
	/**
	 * 根据关键词得出该歌曲链接，默认取第一个
	 * @param keyword（格式 歌曲名  歌手名（为提高检索效率，两者之间有空格） 如大海  张雨生）
	 * @return
	 */
	public static String getViedoUrl(String keyword){
		HtmlCleaner cleaner = new HtmlCleaner();
		InputStream in = getVideoStream(keyword);
		if(in == null){
			return null;
		}
		String targetUrl = null;
		try {
			TagNode rootNode = cleaner.clean(in);
			Object[] items = rootNode.evaluateXPath(VIDEO_LIST_XPATH);
			if(items != null && items.length > 0){
				TagNode item = (TagNode) items[0];
				String href = item.getAttributeByName("href");
				if(href != null && href.indexOf("video") > -1){
					targetUrl = HOST_URL + href;
				}
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				in = null;
			}
		}
		return targetUrl;
	}
	/**
	 * 根据关键词请求网址，获取链接对应的流
	 * @param keyword
	 * @return
	 */
	private static InputStream getVideoStream(String keyword){
		InputStream inStream = null;
		try {
			URL url = new URL(BASE_URL + URLEncoder.encode(keyword, "UTF-8"));
			HttpURLConnection conn;
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(20000);
			conn.setDoOutput(true);
			int respCode = conn.getResponseCode();
			if (respCode == 200) {
				inStream = conn.getInputStream();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return inStream;
	}
	
	public static void main(String[] args) {
		String keyword = "大海  张雨生";
		System.out.println(FetchVideoUrlUtil.getViedoUrl(keyword));
	}
}
